import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:imath/config/constants.dart';
import 'package:imath/db/Storage.dart';

// 从存储中读取数学级别，如果不存在则使用默认值
MATH_LEVEL _getInitialMathLevel() {
  final storedValue = GStorage.userInfo.get('mathLevel');
  if (storedValue != null) {
    try {
      return MATH_LEVEL.values.firstWhere(
        (level) => level.name == storedValue,
        orElse: () => MATH_LEVEL.Primary,
      );
    } catch (e) {
      return MATH_LEVEL.Primary;
    }
  }
  return MATH_LEVEL.Primary;
}

// 保存数学级别到存储
void _saveMathLevel(MATH_LEVEL level) {
  GStorage.userInfo.put('mathLevel', level.name);
}

final mathLevelProvider =
    StateNotifierProvider<MathLevelNotifier, MATH_LEVEL>((ref) {
  return MathLevelNotifier();
});

class MathLevelNotifier extends StateNotifier<MATH_LEVEL> {
  MathLevelNotifier() : super(_getInitialMathLevel());

  void setMathLevel(MATH_LEVEL level) {
    state = level;
    _saveMathLevel(level);
  }
}
